package com.roc.web.action.windcontroll;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.BlackListBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.BlackList;
import com.roc.pojo.Operators;
import com.roc.pojo.TblTfrHisTrnLog;
import com.roc.service.IExcelService;
import com.roc.service.ServiceException;
import com.roc.service.black.IBlackService;
import com.roc.util.Constance;
import com.roc.util.Utils;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.web.action.OperatorQueryAction;
import com.roc.web.action.estrn.RiskEstrnHisInfoSearchCondition;
@SuppressWarnings("serial")
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/blacklist")
public class BlackListsAction extends PaginationBaseAction {
	private Logger logger=LogManager.getLogger(BlackListsAction.class);
	private BlackListsSearchCondition searchCondition;
	private BlackListBean black;
	private File file;
	private String blackNum;
	private InputStream excelFile;
	@Autowired
	IPageService pagenitionService;
	@Autowired
	IBlackService blackService;
	@Autowired
	IExcelService excelService;
	/**
	 * 初始化黑名单页面
	 * @return
	 * @throws Exception
	 */
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/windControllSta/blacklist.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })	
	public String init() throws Exception{
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) || op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())|| op.getRoleType().equals(Role.SYSTEM.getCode()))
		{
			return SUCCESS;
		}
		addActionError("无权限访问!!!");
		return ERROR;	   
    }
	/**
	 * 导出黑名单
	 * @throws IOException 
	 */
	@Action(value = "exportBlackList", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/pages/windControllSta/blacklist.jsp") })
	public String exportBlackList() throws Exception {
		 logger.info("导出黑名单");
			
			if(searchCondition==null){
				searchCondition=(BlackListsSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new BlackListsSearchCondition();
				}
			}
			/*if("".equals(Constance.Null2EmptyTrim(searchCondition.getMinDate()))){
				logger.info("历史交易导出导出条件为空");
				return "error";
			}*/
			try {
				
				int rows=pagenitionService.countSQL(searchCondition);
				if(rows>0){
					searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
				}
				
				List<BlackListBean> blackList = new ArrayList<BlackListBean>();
				queryBlackList(blackList,searchRsList);
				
				
				SXSSFWorkbook work=excelService.exportBlackList(blackList,searchCondition.getMinDate(),searchCondition.getMaxDate());

				 ByteArrayOutputStream output = new ByteArrayOutputStream();  
				       work.write(output);  
				   
				        byte[] ba = output.toByteArray();  
				         excelFile = new ByteArrayInputStream(ba);  
				         output.flush();  
				         output.close();  
				
	}catch (ServiceException e) {
		e.printStackTrace();
		logger.error(e.getMessage(),e);
		addActionError(e.getMessage());
		
	}
	
	return SUCCESS;
}
	/**
	 * 批量导入初始化页面
	 * @return
	 */
	@Action(value = "startExportJsp", results = { @Result(name = "success", location = "/pages/windControllSta/exportBlack.jsp")
    })	
	public String moreBlackList()throws Exception
	{
		return SUCCESS;
	}
	/**
	 * 黑名单列表页面(查询)
	 * @return
	 * @throws Exception
	 */
	@Action(value = "blacklistview", results = { @Result(name = "success", location = "/pages/windControllSta/blacklist.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String blackView() throws Exception{
		logger.info("查询黑名单");
		try {
			if(searchCondition==null){
				searchCondition=(BlackListsSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new BlackListsSearchCondition();
				}
			}
			/*logger.info("查询条件："+"交易日期："+searchCondition.getMinDate()+"-"+searchCondition.getMaxDate());
			if("".equals(Constance.Null2EmptyTrim(searchCondition.getMinDate()))){
				logger.info("历史交易查询查询条件时间为空");
				return SUCCESS;
			}*/
			
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			List<BlackListBean> blackList = new ArrayList<BlackListBean>();
			queryBlackList(blackList,searchRsList);
			
			getRequest().setAttribute("blackList", blackList);
			this.setTotalPage(this.calcuTotalPage(rows));
			//getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
			
			
			/*getRequest().setAttribute("blackList", blackList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);*/
			
		} catch (Exception e) {
			
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}		
	   return SUCCESS;
    }
	
	/**
	 * 查询
	 */
	 public  void queryBlackList(List<BlackListBean> blackList,List<Object> searchRsList){
		 Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		    
			if(searchRsList!=null&&searchRsList.size()>0){
				Iterator iterator=searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj=(Object[]) iterator.next();
					BlackListBean bean=new BlackListBean();
					bean.setBlackNum(Constance.Null2EmptyTrim(obj[0]));
					bean.setBlackType(Constance.Null2EmptyTrim(obj[1]));
					bean.setDate(Constance.Null2EmptyTrim(obj[2]));
					bean.setTime(Constance.Null2EmptyTrim(obj[3]));
					bean.setReason(Constance.Null2EmptyTrim(obj[4]));
					bean.setStatus(Constance.Null2EmptyTrim(obj[5]));
					blackList.add(bean);
			}
			
			
		}
	 }
	/**
	 * 初始化添加黑名单
	 * @return
	 */
	@Action(value = "addblackjsp", results = { @Result(name = "success", location = "/pages/windControllSta/addBlack.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String addBlackview()
	{
		black=new BlackListBean();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		String date=sdf.format(new Date());
		black.setDate(date.substring(0, 8));
		black.setTime(date.substring(8));
		return SUCCESS;		
	}
	/**
	 * 添加黑名单
	 * @return
	 */
	@Action(value = "addblack", results = { @Result(name = "success", location = "/pages/windControllSta/blacklist.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String addBlackList()
	{
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			blackService.addBlackList(black,logingMerchant);
			addActionMessage("添加成功!");
		} catch (ServiceException e) {
			e.printStackTrace();
			addActionError("添加黑名单失败~");
		}
		return SUCCESS;		
	}
	/**
	 * 批量导入黑名单
	 * @return
	 */
	@Action(value = "addblacklist", interceptorRefs = {
			@InterceptorRef(value = "token"),
			@InterceptorRef(value = "rocDefaultStack", params = {
					"fileUpload.allowedExtensions", "xlsx",
					"fileUpload.maximumSize", "100000000" }) }, results = {
			@Result(name = "success",location = "/pages/windControllSta/exportBlack.jsp"),
			@Result(name = "error", location = "/error.jsp"),
			@Result(name = "invalid.token", location = "/error.jsp")})
	public String addBlackLists()
	{
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			Map<String, Object> resultMap=blackService.insertExportBlackList(file, logingMerchant);
			if(resultMap.containsKey("result"))
			{	
				Object objMsg=resultMap.get("result");
				addActionMessage(String.valueOf(objMsg));
			}		
		} catch (ServiceException e) {
			e.printStackTrace();
			addActionError("批量导入黑名单失败~");
		}
		return SUCCESS;		
	}
	/**
	 * 修改页面初始化
	 * @return
	 */
	@Action(value = "updateBlacklistInit", results = { @Result(name = "success", location="/pages/windControllSta/addBlack.jsp")})
	public String updateInit()
	{
		try {
			black=blackService.findByBlackNum(black.getBlackNum());
			SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
			String date=sdf.format(new Date());
			black.setDate(date.substring(0, 8));
			black.setTime(date.substring(8));
			getRequest().setAttribute("flag", "update");
		} catch (ServiceException e) {
			e.printStackTrace();
			e.getMessage();
			addActionError("修改页面初始化失败~");
		}
		return SUCCESS;
	}
	/**
	 * 更改黑名单
	 * @return
	 */
	@Action(value = "updateBlacklist", results = { @Result(name = "success", location="/pages/windControllSta/blacklist.jsp")})
	public String updateStatus()
	{
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			black.setBlackNum(blackNum);
			blackService.updateBlackList(black,logingMerchant);
			addActionMessage("修改成功!");
		} catch (ServiceException e) {
			e.printStackTrace();
			addActionError("更改状态失败~");
		}
		return SUCCESS;
	}
	@Action(value = "delBlacklist", results = { @Result(name = "success", type="json")})
	public String delBlackList()
	{
		try {
			blackService.delBlackListByBlackNum(black.getBlackNum());		
		} catch (ServiceException e) {
			e.printStackTrace();
			addActionError("删除黑名单失败~");
		}
		return SUCCESS;
	}
	 /**
	  * 验证卡号或商户号是否已存在数据库中
	  */
	@Action(value="validateBlackNum")
	public void validateBlackNum()
	{
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		boolean value=true;
		try {
			black=blackService.findByBlackNum(black.getBlackNum());
			if(black!=null)
			{
				value=false;
			}
			response.getWriter().print(value);
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			addActionError("验证卡号或商户号错误!!!");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {

		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {

		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {

		getSession().setAttribute(SEARCH_SESSION_BLACK_LIST_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {

		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_BLACK_LIST_QUERY);
	}

	@Override
	protected String getInitPageSize() {

		return Constance.PAGE_MAX_SIZE+"";
	}
	public BlackListsSearchCondition getSearchCondition() {
		return searchCondition;
	}
	public void setSearchCondition(BlackListsSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	public BlackListBean getBlack() {
		return black;
	}
	public void setBlack(BlackListBean black) {
		this.black = black;
	}
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}
	public String getBlackNum() {
		return blackNum;
	}
	public void setBlackNum(String blackNum) {
		this.blackNum = blackNum;
	}
	public InputStream getExcelFile() {
		return excelFile;
	}
	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}
	public String getExcelName() {
		String excelName="黑名单"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}
}
